<?php
/**

*/
class LoginController extends App_Controller_Action
{
	public function init()
	{
		/* Initialize action controller here */
	}

	public function preDispatch()
	{
		$user = $this->getUserId();
		if (!empty($user)) {
			$user_role = $this->getUserRole();
			// If the user is logged in, we don't want to show the login form;
			// however, the logout action should still be available
			
			if ('logout' != $this->getRequest()->getActionName()) {

				if ($user_role == 'admin') $this->_redirect('/admin');
				else $this->_redirect('/client');
			}

		} else {

			// If they aren't, they can't logout, so that action should redirect to the login form
			if ('logout' == $this->getRequest()->getActionName()) {
			}
		}
	}

	public function indexAction()
	{
		 
	}

	public function adminAction()
	{
		// this action does not use a layout
		//$this->_helper->layout->disableLayout();

		$request = $this->getRequest();

		$form = new Form_Login();
		$form->setAction('/login/admin');
		$this->view->form = $form;

		if ($this->getRequest()->isPost()) {

			$formData = $this->getRequest()->getPost();

			//check IP
			$ip=Model_ActionLog::getIp();
			if (($ip!='70.50.227.211')and($ip!='199.21.151.11')and($ip!='127.0.0.1')and(substr($ip,0,10)!='192.168.25')and(substr($ip,0,10)!='192.168.26')){
				$this->view->formError = 'IP address not allowed.';				
			}else{

				if ($form->isValid($formData)) {
	
					$username = $form->getValue('username');
					$password = $form->getValue('password');
					$redirect_url = $form->getValue('_redirect_url');
	
					$session = $this->getSession();
	
					// create components for authentication
					$storage = new App_Auth_Storage_Session($session, $request->getActionName());
					$adapter = new App_Auth_Adapter_Web($username, $password);
					$auth = Zend_Auth::getInstance();
					$auth->setStorage($storage);
	
					// authenticate the user (note: authorization is in Access Plugin)
					$result = $auth->authenticate($adapter);
					if (!$result->isValid()) {
						// invalid credentials
						$form->populate(array('username' => $username, '_redirect_url' => $redirect_url));
						$this->view->formError = 'Invalid username and/or password.';
						return; // re-render the login form
					}
	
					//$user_area =  $storage->getUserArea();
					// redirect to the intended destination of the caller
					if (!empty($redirect_url)){
						$this->_redirect($redirect_url);
					}
					else{
						// if no redirect url - send the user to the 'dashboard' page
						$this->_redirect("/admin");
					}
				} else {
					$form->populate($formData);
				}
			}
		}
		else{

			// set the redirect uri field on the form (original location where the user was going)
			$form->setRedirectUrl($request->getParam('_request_url'));
		}

	}

	public function clientAction()
	{
		// this action does not use a layout
		//$this->_helper->layout->disableLayout();
		
		$model_service = new Model_Service();
    	$all_services = $model_service->getAllService();  			
		$this->view->all_services=$all_services;		
		
		$err= false;
		$client_id = "";

		$request = $this->getRequest();
		$msg = $request->getParam('msg');
		$this->view->msg = $msg;
		
		$form = new Form_ClientLogin();
		$form->setAction('/login/client');
		$this->view->form = $form;

		
		if ($this->getRequest()->isPost()) {

			//check IP
			$ip=Model_ActionLog::getIp();
			if ( 1== 0 ){
				$this->view->formError = 'IP address not allowed.';				
			}else{
			
				$formData = $this->getRequest()->getPost();
				if ($form->isValid($formData)) {
	
					$dpt_id = $form->getValue('dpt_id');
					$dpt_account_login = $form->getValue('username');
					$dpt_password = $form->getValue('password');
					$redirect_url = $form->getValue('_redirect_url');
					$from_dpt = $request->getParam('from_dpt');
					$fail_callback = $request->getParam('fail_callback');
					
					$model_client = Model_UserFactory::create('client');
					$dpt_login = $model_client->dptLoginCheck($dpt_id, $dpt_account_login, $dpt_password);
					//Zend_Debug::dump($dpt_login);//exit;
					if ($dpt_login['status'] === true)
					{
						$dpt_account_id = $dpt_login['dpt_account_id'];
						if ($dpt_login['login_area']!='central'){ //not from central account						
						
							$model_service = new Model_Service();
							$client_id = $model_service->getClientServiceInfo($dpt_id, $dpt_account_login);
							if ($client_id === -1)
							{
								//$client_id = $model_client->linkClientService($user_id, $dpt_id, $dpt_account_id, $dpt_login_arr);
							  $form->populate(array('username' => $dpt_account_login, '_redirect_url' => $redirect_url));
							  $dpt_login['message'] = 'Not subscribed yet.';
							  $err= true;
							}
							elseif ($client_id === -2) 
							{
							  $form->populate(array('username' => $dpt_account_login, '_redirect_url' => $redirect_url));
							  $dpt_login['message'] = 'Please use the YesUp account to login.';
							  $err= true;
							}
							else 
							{
								$dpt_login_arr=array();
								$dpt_login_arr['dpt_account_login'] = $dpt_account_login;
								$dpt_login_arr['login_area'] = $dpt_login['login_area'];
								$dpt_login_arr['email'] = $dpt_login['email'];
								$dpt_account_id = $dpt_login['dpt_account_id'];
								
							}								
						}else{ //from central account
							$client_id = $dpt_login['dpt_account_id'];
								
						}
					}
					else
					{
						$form->populate(array('username' => $dpt_account_login, '_redirect_url' => $redirect_url));
						$this->view->formError = $dpt_login['message'];
	
						$err= true;
						
						if ($from_dpt=='3009'){
							$fail_callback = str_replace('[msg]',$dpt_login['message'],$fail_callback);
							$this->_redirect($fail_callback);
						}
					}
	
					if ($client_id !== -1 && $client_id !== -2 && $client_id && !$err)
					{
						$client = $model_client->getClient($client_id);	
						$session = $this->getSession();
						$storage = new App_Auth_Storage_Session($session,'client');
						//Zend_Debug::dump($storage->read());		
						$storage->write(array(
	                    'user_id'=>$client_id,
	                    'user_name'=>$dpt_account_login,
	                    'user_role'=>$client['role']));
						//Zend_Debug::dump($storage->read());exit;
						
						//for action log
						$data=array();
						$data['ip'] = Model_ActionLog::getIp();			
						$data['user_id'] = $dpt_account_login;
						$data['client_id'] = $client_id;
						$data['dpt_id'] = $dpt_id;
						$data['dpt_account_id'] = '';
						$data['action'] = 'login';
						$data['memo'] = "/login";			
						Model_ActionLog::actionLog($data);
						
						if (($from_dpt=='3009')or($from_dpt=='3010')){
							$dpt_service=$model_service->getClientDptService($from_dpt, $client_id);
							if (!empty($dpt_service)){
								$account_id = $dpt_service['dpt_account_id'];
								$this->_redirect('/client/index/to-service/did/'.$from_dpt.'/aid/'.$account_id.'/cid/'.$client_id);
							}
						}						
						
					}
					elseif ($err) {
						// invalid credentials
						$form->populate(array('username' => $dpt_account_login, '_redirect_url' => $redirect_url));
						$this->view->formError = $dpt_login['message'];
						return; // re-render the login form
					}
	
					// redirect to the intended destination of the caller
					if (!empty($redirect_url)){
						$this->_redirect($redirect_url);
					}
					else{
						// if no redirect url - send the user to the 'dashboard' page
						$this->_redirect("/client");
					}
	
				} else {
	
					$form->populate($formData);
				}
			}
		}
		else
		{
			// set the redirect uri field on the form (original location where the user was going)
			$form->setRedirectUrl($request->getParam('_request_url'));
		}

	}
	
	
	public function googleOpenidAction()
	{
		$err= false;
		$client_id = "";

		$request = $this->getRequest();
		$msg = $request->getParam('msg');
		$this->view->msg = $msg;
		
		$form = new Form_ClientLogin();
		$form->setAction('/login/client');
		$this->view->form = $form;
		
		$user_id = "";
		$user_email = "";
		$googleLogin = App_GoogleOpenID::getResponse();
    	if($googleLogin->success()){
		    $user_id = $googleLogin->identity();
		    $user_email = $googleLogin->email();
		}
    	//Zend_Debug::dump($user_id);
    	//Zend_Debug::dump($user_email);
		if ($user_id && $user_email)
    	{
    		$model_client = Model_UserFactory::create('client');
    		$client_info = $model_client->getClientByEmail($user_email);	
    		//Zend_Debug::dump($client_info);
    		
    		$err = false;
    		if (!$client_info)
    		{	
    			$id_type='google';
    			$model_client->signupClient($user_email,$user_id,$id_type);
    			$client_info = $model_client->getClientByEmail($user_email);
    		}
    		else 
    		{
    			$user_status = $client_info['status'];
    			$id_type = $client_info['id_type'];
    			if ($id_type != 'google' )
    			{
    				$form->populate(array('username' => $user_email, '_redirect_url' => ''));
					$this->view->formError = 'Email address is used by another YesUp Account';
					$err = true;
					
					return;
    			}
    			else 
    			{
    				if ($user_status != 'Active')
    				{
    					$form->populate(array('username' => $user_email, '_redirect_url' => ''));
    					$this->view->formError = 'Email address is disabled.';
    					$err = true;
    					return;
    				}
    			}	
    		}
    		
    		if (!$err)
    		{
    			$client_id = $client_info['client_id'];
    			
    			$session = $this->getSession();
				$storage = new App_Auth_Storage_Session($session,'client');
				//Zend_Debug::dump($storage->read());		
				$storage->write(array(
                    'user_id'=>$client_id,
                    'user_name'=>$user_email,
                    'user_role'=>$client_info['role']));
				//Zend_Debug::dump($storage->read());exit;
				$this->_redirect("/client");
    		}
    		
    			
    	}
    	exit;
	}


	public function forgetPasswordAction()
	{
    	$request=$this->getRequest();
    	if($request->isPost())
    	{
    		$email = $request->getParam('email');    	    		
    		$this->view->email = $email;
/*    		
    		$new_password = Model_UserClient::str_makerand (6, 8);     		
			$model_client = new Model_UserClient();
			$result = $model_client->udpatePassword($email,$new_password);
*/    		
			
			$model_client = new Model_UserClient();
			$clientInfo = $model_client->getClientByEmail($email);
    		
			if ($clientInfo){
				
				$id=$clientInfo['client_id'];
				$key=$clientInfo['password'];
				
				$body = "Dear YesUp User,<br><br>
				
							Please click the link to reset your YesUp account password.<br><br>
							<a href='http://account.yesup.com/reset/index/id/".$id."/key/".$key."'>http://account.yesup.com/reset/index/id/".$id."/key/".$key."</a><br><br>
							
							Best regards,<br><br>
							
							YesUp Account Support Team<br>
								    			";
			    $mail = new Zend_Mail('UTF-8');
			    $mail->setBodyHtml($body)
			         ->setFrom('no-reply@yesup.com', 'YesUp Account')
			         ->addTo($email, '')
			         ->setSubject("Reset Your YesUp Account Password")
			         ->send();    			
    		
/*
    			$body = "Dear YesUp User,<br><br>
							Your account information is:<br><br>
							
							YesUp Account Username: ".$email." <br>
							New Password: ".$new_password." <br><br>
							
							Please login with this new password and you can also reset your password after login.<br><br>
							
							Best regards,<br><br>
							
							YesUp Account Support Team<br>
								    			";
			    $mail = new Zend_Mail('UTF-8');
			    $mail->setBodyHtml($body)
			         ->setFrom('no-reply@yesup.com', 'YesUp Account')
			         ->addTo($email, '')
			         ->setSubject("Your New YesUp Account Password")
			         ->send();    			
*/			         
			         
				//$this->_redirect("/default/login/client/msg/signup");	
				$this->_redirect("/login/forget-confirm");	
				
			}else{
				$this->view->error_msg="Sorry, account email is not found in system.";					
			}
			
    	}
	}
	
	public function forgetConfirmAction()
	{
	}
	
	
	public function boxAction()
	{
		$model_service = new Model_Service();
    	$all_services = $model_service->getAllService();  			
		$this->view->all_services=$all_services;		
    	$all_groups = $model_service->getAllGroup();  			
		$this->view->all_groups=$all_groups;			
	}
	
	// this action destroys all elements stored in the user's session
	// and redirects back to homepage
	public function logoutAction()
	{
		$session = $this->getSession();
		$session->unsetAll();

		$this->_redirect('/');
	}





}
